package com.guazai.project.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.guazai.common.pojo.ProductInfo;
import com.guazai.project.common.ErrorCode;
import com.guazai.project.exception.BusinessException;
import com.guazai.project.mapper.ProductInfoMapper;
import com.guazai.project.model.dto.productinfo.ProductInfoQueryRequest;
import com.guazai.project.model.enums.ProductTypeEnum;
import com.guazai.project.model.vo.ProductInfoVO;
import com.guazai.project.service.ProductInfoService;
import com.guazai.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yiyan
 * @description 针对表【product_info(产品信息)】的数据库操作Service实现
 * @createDate 2024-08-20 15:13:51
 */
@Service
@Slf4j
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo>
        implements ProductInfoService {
    private final static Gson GSON = new Gson();

    @Resource
    private UserService userService;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 非空判断
     *
     * @param productInfo
     * @param add
     */
    @Override
    public void validProductInfo(ProductInfo productInfo, boolean add) {
        if (productInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String name = productInfo.getName();
        String description = productInfo.getDescription();

        Long addGoldCoin = productInfo.getAddGoldCoin();


        // 创建时，参数不能为空
        if (add) {
            if (StringUtils.isAnyBlank(name)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "名称必填！");
            }
        }
        // 有参数则校验
        if (ObjUtil.isNotEmpty(addGoldCoin) && name.length() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "添加金币数不正确");
        }
        if (StringUtils.isNotBlank(description) && description.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "描述过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param productInfoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<ProductInfo> getQueryWrapper(ProductInfoQueryRequest productInfoQueryRequest) {
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        if (productInfoQueryRequest == null) {
            return queryWrapper;
        }
        Long id = productInfoQueryRequest.getId();
        String searchText = productInfoQueryRequest.getSearchText();
        String name = productInfoQueryRequest.getName();
        String description = productInfoQueryRequest.getDescription();
        Long total = productInfoQueryRequest.getTotal();
        Long addGoldCoin = productInfoQueryRequest.getAddGoldCoin();
        Integer status = productInfoQueryRequest.getStatus();
        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.like("name", searchText).or().like("description", searchText);
        }
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(total), "total", total);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(addGoldCoin), "addGoldCoin", addGoldCoin);
        queryWrapper.eq("isDelete", false);
        return queryWrapper;
    }

    @Override
    public ProductInfoVO getProductInfoVO(ProductInfo productInfo, HttpServletRequest request) {
        // 转为vo对象
        ProductInfoVO productInfoVO = ProductInfoVO.objToVo(productInfo);
        return productInfoVO;
    }

    @Override
    public ProductInfo getProductInfoById(Long id) {
        return this.getById(id);
    }

    @Override
    public Page<ProductInfoVO> getProductInfoVOPage(Page<ProductInfo> productInfoPage) {
        List<ProductInfo> productInfoList = productInfoPage.getRecords();
        Page<ProductInfoVO> productInfoVOPage = new Page<>(productInfoPage.getCurrent(), productInfoPage.getSize(), productInfoPage.getTotal());
        if (CollectionUtils.isEmpty(productInfoList)) {
            return productInfoVOPage;
        }
        List<ProductInfoVO> productInfoVOList = productInfoList.stream().map(productInfo -> {
            ProductInfoVO productInfoVO = new ProductInfoVO();
            BeanUtil.copyProperties(productInfo, productInfoVO);
            return productInfoVO;
        }).collect(Collectors.toList());
        // 2. 已登录，获取用户点赞、收藏状态
        // 填充信息
        productInfoVOPage.setRecords(productInfoVOList);
        return productInfoVOPage;
    }


    @Override
    public Page<ProductInfo> listProductInfoByPage(ProductInfoQueryRequest productInfoQueryRequest) {
        long current = productInfoQueryRequest.getCurrent();
        long size = productInfoQueryRequest.getPageSize();
        // 限制爬虫
        if (size > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 从缓存中获取接口分页信息
        // 计算 offset 和 count
        long offset = (current - 1) * size;
        long count = size;
        // 获取redis中的数据
        Page<ProductInfo> page = new Page<>(current, size);
        // 查询数据库
        List<ProductInfo> allProductInfoList = list();
        page.setRecords(allProductInfoList);
        page.setTotal(allProductInfoList.size());
        return page;
    }

    @Override
    public List<ProductInfo> getProductInfoTypeList(ProductTypeEnum productTypeEnum) {
        String productType = productTypeEnum.getValue();
        return list(new QueryWrapper<ProductInfo>().eq("productType", productType));
    }
}




